﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;

namespace WebPortal.Controllers
{
    public class BaseController : Controller
    {
        protected WebPortalEntities1 dbUsers = new WebPortalEntities1();
        protected WebPortalEntities2 dbCategories = new WebPortalEntities2();
        protected WebPortalEntities3 dbGoods = new WebPortalEntities3();
        protected WebPortalEntities5 dbBasket = new WebPortalEntities5();
        protected bool IsRegistredUser = false;
        protected Users User;

        public BaseController()
        {
            IsRegistredUser = LoginByCookies();
            ViewData["IsRegistredUser"] = IsRegistredUser;
            ViewData["IsAdmin"] = User == null ? false : User.IsAdmin;
        }

        protected int LoginByEmail(Users u)
        {
            var users = (from user in dbUsers.Users
                         where
                             (user.Email.ToLower() == u.Email.ToLower()) &&
                             (user.Password.ToLower() == u.Password.ToLower())
                         select user).ToList();
            if (users.Count == 1)
                return users[0].UserID;
            else
                return -1;
        }

        protected bool CookieExists(string name)
        {
            return System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains<string>(name);
        }

        protected HttpCookie GetCookie(string name)
        {
            return System.Web.HttpContext.Current.Request.Cookies.Get(name);
        }

        protected bool LoginByCookies()
        {
            bool result = false;
            if (CookieExists("userID") && CookieExists("pass"))
            {
                Users _user = new Users();
                try
                {
                    _user.UserID = Convert.ToInt32(GetCookie("userID").Value);
                }
                catch (FormatException ex)
                {
                    return result;
                }
                _user.Password = GetCookie("pass").Value;
                var users = (from u in dbUsers.Users
                            where
                                (_user.UserID == u.UserID) &&
                                (_user.Password.ToLower() == u.Password.ToLower())
                            select u).ToList();
                if (users.Count == 1)
                {
                    result = true;
                    User = users[0];
                }
            }
            return result;
        }
    }
}